<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        input {
            margin-top: 20px;
        }

        div {
            margin-top: 30px;
            width: 150px;
            height: 150px;
            background-color: greenyellow;
            /* div要脱离文档流  position: absolute*/
            position: absolute;
            left: 50px;
        }
    </style>
</head>

<body>
    <input type="button" value="移动到400px" id="btn1" />
    <input type="button" value="移动到800px" id="btn2" />
    <div id="dv"></div>
    <script>
        function my$(id) {
            return document.getElementById(id);
        }
        my$("btn1").onclick = function () {
            var timeId = setInterval(function () {
                //获取当前div当前left的位置
                var left = my$("dv").offsetLeft;
               if(left < 400){
                    left += 10;
                    my$("dv").style.left = left + "px";
                } else if(left > 400){
                    left -= 10;
                    my$("dv").style.left = left + "px";
                }else {
                    clearInterval(timeId);
                }
            }, 20)
        }

        my$("btn2").onclick = function () {
            var timeId = setInterval(function () {
                //获取当前div当前left的位置
                var left = my$("dv").offsetLeft;
                if (left >= 800) {
                    clearInterval(timeId);
                } else {
                    left += 10;
                    my$("dv").style.left = left + "px";
                }
            }, 20)
        }

    </script>
</body>

</html>